package com.icngor.web;

import com.icngor.dao.GirlRepository;
import com.icngor.config.GirlProperties;
import com.icngor.domain.Result;
import com.icngor.entity.Girl;
import com.icngor.exception.GirlException;
import com.icngor.service.GirlService;
import com.icngor.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by Administrator on 2017/4/8 0008.
 */
@org.springframework.web.bind.annotation.RestController
public class RestController {

//    @Value("${cupSize}")
//    private String cupSize;

    @Autowired
    private GirlProperties girlProperties;

    @Autowired
    private GirlRepository girlRepository;

    @Autowired
    private GirlService girlService;

    /**
     * 查询所有女生
     *
     * @return
     */
    @GetMapping("/girls")
    public List<Girl> girls() {
        System.out.println(girlProperties.getCupSize());
        return girlRepository.findAll();
    }

    /**
     * 添加一个女生
     *
     * @return
     */
    @PostMapping("/girls")
    public Result<Girl> girlsAdd(@Valid Girl girl, BindingResult result) {

        if (result.hasErrors()) {
            return ResultUtil.error(1, result.getFieldError().getDefaultMessage());
        }
        girl.setCupSize(girl.getCupSize());
        girl.setAge(girl.getAge());

        return ResultUtil.success(girlRepository.save(girl));
    }

    @GetMapping("/girls/{id}")
    public Girl girlFindOne(@PathVariable("id") Integer id){
        System.out.println(id);
        return girlRepository.findOne(id);
    }

    @PutMapping("/girls/{id}")
    public Girl girlUpdate(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize){
        Girl girl = new Girl();
        girl.setId(id);
        girl.setCupSize(cupSize);
        return girlRepository.save(girl);
    }

    @DeleteMapping("/girls/{id}")
    public void deleteGirl(@PathVariable("id") Integer id) {
        girlRepository.delete(id);
    }

    @GetMapping("girls/age/{cupSize}")
    public List<Girl> girlListByAge(@PathVariable("cupSize") String cupSize){
        return girlRepository.findBycupSize(cupSize);
    }

    @GetMapping("girls/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws GirlException {
        girlService.getAge(id);
    }
//    @Transactional   事务
}
